package com.xiaoxin.myhouse.config;

import java.util.LinkedHashMap;

import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.xiaoxin.myhouse.AuthRleam;
import com.xiaoxin.myhouse.CredentiaMatcher;

@Configuration
public class ShiroConfiguration {
	
	@Bean("shiroFilter")
	public ShiroFilterFactoryBean shiroFilter(@Qualifier("securityManager") SecurityManager manager) {
		ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
		bean.setSecurityManager(manager);
		bean.setLoginUrl("/login");
		bean.setSuccessUrl("/index");
		bean.setUnauthorizedUrl("/unauthorized");
		LinkedHashMap<String, String> map = new LinkedHashMap<>();
		map.put("/index/**", "authc");
		map.put("/login/**", "anon");
		map.put("/druid/**", "anon");
		map.put("/loginUser", "anon");
		map.put("/admin", "roles[admin]");
		map.put("/edit", "perms[edit]");
		map.put("/logout", "logout");
		map.put("/**", "user");
		bean.setFilterChainDefinitionMap(map);
		return bean;
		
	}
	
	@Bean("securityManager")
	public SecurityManager securityManager(@Qualifier("authRleam") AuthRleam rleam) {
		DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
		manager.setRealm(rleam);
		return manager;
	}
	
	
	@Bean("authRleam")
	public AuthRleam authRealm(@Qualifier("credentiaMatcher") CredentiaMatcher credentiaMatcher) {
		AuthRleam authRleam = new AuthRleam();
		authRleam.setCredentialsMatcher(credentiaMatcher);
		//设置缓存
		authRleam.setCacheManager(new MemoryConstrainedCacheManager());
		return authRleam;
	}
	
	@Bean("credentiaMatcher")
	public CredentiaMatcher credentiaMatcher() {
		return new CredentiaMatcher();
	}

	@Bean
	public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(@Qualifier("securityManager") SecurityManager manager) {
		AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
		advisor.setSecurityManager(manager);
		return advisor;
		
	}
	@Bean
	public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
		DefaultAdvisorAutoProxyCreator creator = new DefaultAdvisorAutoProxyCreator();
		creator.setProxyTargetClass(true);
		return creator;
		
	}
}
